package com.firmiana.jt809.service;

import com.firmiana.jt809.config.GlobalConfig;
import com.firmiana.jt809.connection.ConnectionManager;
import com.firmiana.jt809.entity.BizConnection;
import com.firmiana.jt809.entity.JT809Message;
import com.firmiana.jt809.netty.sub.NettyTCPSubLink;
import com.firmiana.jt809.protocol.send.SubLinkConnectRequest;
import com.firmiana.jt809.protocol.send.SubLinkSendHeartBeat;
import com.firmiana.jt809.util.FunctionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 从链路服务
 * @author hucl
 * @date 2020/8/26 15:32
 */
@Service
@Slf4j
public class SubLinkService {

    public NettyTCPSubLink createSubLink(String host, int port) {
        NettyTCPSubLink subLink = new NettyTCPSubLink(host, port);
        subLink.init();
        subLink.start(new Listener() {
            @Override
            public void onSuccess(Object... args) {
                log.info("start successfully on:{}", args);
            }

            @Override
            public void onFailure(Throwable cause) {
                log.error("", cause);
            }
        });
        return subLink;
    }

    public boolean sendMessage(JT809Message msg) {
        String strMsg = FunctionUtils.getHeaderAndFlag(GlobalConfig.getSN(),
                msg.getMessageBody(), msg.getMsgType(),
                msg.getMsgGNSSCenterID(), false);
        msg.setPacketDesc(strMsg);
        msg.setRemark("从下行 MSG!");
        BizConnection conn = ConnectionManager.get(String.valueOf(msg.getMsgGNSSCenterID()));
        if (conn != null) {
            return conn.getSubLink().sendMessage(msg.toHexString());
        }
        return false;
    }

    /**
     * 从链路连接请求
     * 业务数据类型标识：DOWN_CONNECT_REQ
     * 0x9001
     *
     * @param platformId 平台id
     * @return
     */
    public boolean subConnectRequest(String platformId) {
        SubLinkConnectRequest slcr = new SubLinkConnectRequest(platformId);
        JT809Message wrap = slcr.wrap();
        wrap.setMsgGNSSCenterID(Long.parseLong(platformId));
        return sendMessage(wrap);
    }

    /**
     * 从链路心跳检测
     * @param platformId 平台id
     * @return
     */
    public boolean subLinkHeartBeatRequest(String platformId) {
        SubLinkSendHeartBeat subLinkSendHeartBeat = new SubLinkSendHeartBeat();
        JT809Message wrap = subLinkSendHeartBeat.wrap();
        wrap.setMsgGNSSCenterID(Long.parseLong(platformId));
        return sendMessage(wrap);
    }
}
